<template>
  <div class="daochu-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-button-group>
          <el-button 
            type="primary" 
            icon="el-icon-data-analysis"
            @click="calculateData">
            计算数据
          </el-button>
          <el-button 
            type="success" 
            icon="el-icon-download"
            @click="exportToExcel" 
            :disabled="!calculatedData">
            导出 Excel
          </el-button>
        </el-button-group>
      </el-col>
    </el-row>

    <!-- 显示计算结果 -->
    <div v-if="calculatedData" class="results-section">
      <!-- 统计信息卡片 -->
      <el-card class="stats-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>计算结果统计</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="最大值" :precision="3" :value="calculatedData.minMaxData[1][0]">
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic title="最小值" :precision="3" :value="calculatedData.minMaxData[1][1]">
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic title="差值" :precision="3" :value="calculatedData.minMaxData[1][2]">
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic title="刀数" :value="calculatedData.minMaxData[1][3]">
            </el-statistic>
          </el-col>
        </el-row>
      </el-card>

      <!-- 数据表格卡片 -->
      <el-card class="table-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>详细数据</span>
          <el-radio-group 
            v-model="currentSheet" 
            size="small" 
            class="sheet-selector"
            @change="handleSheetChange"
          >
            <el-radio-button label="sheet1">原始数据</el-radio-button>
            <el-radio-button label="sheet3">计算结果</el-radio-button>
            <el-radio-button 
              v-for="i in calculatedData.dividedDifference" 
              :key="i" 
              :label="`cvn${i}`"
            >#{{ i }}</el-radio-button>
          </el-radio-group>
        </div>

        <el-table
          :data="paginatedData"
          style="width: 100%"
          :header-cell-style="tableHeaderStyle"
          :cell-style="tableCellStyle"
          border
          stripe
          height="500"
          v-loading="tableLoading"
        >
          <el-table-column
            v-for="(header, index) in currentHeaders"
            :key="index"
            :prop="index.toString()"
            :label="header"
            :width="getColumnWidth(header)"
            align="center"
          >
            <template slot-scope="scope">
              <span :class="getCellClass(header, scope.row[index])">
                {{ formatCellValue(scope.row[index]) }}
              </span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加分页器 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalRows"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as XLSX from "xlsx";
import { EventBus } from "@/event";
// import Decimal from 'decimal.js';
export default {
  name: 'DataProcessor',
  data() {
    return {
      receivedData: [],
      calculatedData: null,
      currentSheet: 'sheet1',
      tableLoading: false,
      currentHeaders: [],
      currentTableData: [],
      dataCache: new Map(),
      totalRows: 0,
      currentPage: 1,
      pageSize: 20,
      paginatedData: [],
    };
  },
  created() {
    EventBus.$on("data-sent", (data) => {
      this.receivedData = data;
      this.calculatedData = null;
      this.resetCache();
    });

  },
  methods: {
    calculateMinMax(data) {
      let max = -Infinity;
      let min = Infinity;

      for (let i = 0; i < data.length; i++) {
        const value = data[i][3]; // 高程在第四列
        if (typeof value === "number") {
          if (value > max) max = value;
          if (value < min) min = value;
        }
      }

      const difference = max === -Infinity || min === Infinity ? null : (max - min) * 1000;
      const DK = 35;
      const dividedDifference = difference !== null ? Math.ceil(difference / DK) : null;

      return { max, min, difference, dividedDifference };
    },

    processYValues(data) {
      const yValuesMap = new Map();
      for (let i = 0; i < data.length; i++) {
        const xValue = data[i][1];
        const yValue = data[i][2];
        if (!yValuesMap.has(xValue)) {
          yValuesMap.set(xValue, []);
        }
        yValuesMap.get(xValue).push(yValue);
      }
      return yValuesMap;
    },

    calculateCVNArray(roundedResult, dividedDifference) {
      var cvnArr = Array(dividedDifference).fill(-99);
      if (roundedResult < 35) {
        cvnArr[0] = roundedResult;
      } else {
        cvnArr[0] = 35;
        let nextdeepth = roundedResult - 35;
        for (let j = 1; j < dividedDifference; j++) {
          if (nextdeepth > 35) {
            cvnArr[j] = 35 * (j + 1);
          } else {
            cvnArr[j] = roundedResult;
            break;
          }
          nextdeepth -= 35;
        }
      }
      return cvnArr;
    },

    processSheet3Data(processedData, yValuesMap, max, dividedDifference) {
      const sheet3Data = [
        [
          "编号", "x", "y", "高程", "标记", "打印深度",
          ...Array.from({ length: dividedDifference }).map((_, index) => `CVN_${index + 1}`)
        ]
      ];

      for (let i = 0; i < processedData.length; i++) {
        let xValue = processedData[i][1];
        let correspondingYValues = yValuesMap.get(xValue);

        if (correspondingYValues) {
          let maxY = Math.max(...correspondingYValues);
          let minY = Math.min(...correspondingYValues);
          let yValue = processedData[i][2];
          let label = yValue === maxY ? "B" : yValue === minY ? "A" : "C";
          let roundedResult = Math.round((max - processedData[i][3]) * 1000);
          let cvnArr = this.calculateCVNArray(roundedResult, dividedDifference);

          sheet3Data.push([
            ...processedData[i],
            label,
            roundedResult,
            ...cvnArr
          ]);
        }
      }
      return sheet3Data;
    },

    createWorkbook(originalData, minMaxData, sheet3Data, dividedDifference) {
      const workbook = XLSX.utils.book_new();
      
      // Sheet1 - 原始数据
      const worksheet = XLSX.utils.aoa_to_sheet(originalData);
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

      // Sheet2 - 最大最小值
      const minMaxWorksheet = XLSX.utils.aoa_to_sheet(minMaxData);
      XLSX.utils.book_append_sheet(workbook, minMaxWorksheet, "Sheet2");

      // Sheet3 - 处理后的数据
      const sheet3Worksheet = XLSX.utils.aoa_to_sheet(sheet3Data);
      XLSX.utils.book_append_sheet(workbook, sheet3Worksheet, "Sheet3");

      // 动态CVN工作表
      for (let i = 0; i < dividedDifference; i++) {
        const cvnWorksheetData = [
          ["编号", "x", "y", "标记", `CVN_${i + 1}`],
          ...sheet3Data
            .slice(1)
            .filter(item => item[6 + i] !== -99)
            .map((item) => [
              item[0], item[1], item[2], item[4], item[6 + i]
            ])
        ];
        const cvnWorksheet = XLSX.utils.aoa_to_sheet(cvnWorksheetData);
        XLSX.utils.book_append_sheet(workbook, cvnWorksheet, `${i + 1}#`);
      }

      return workbook;
    },

    calculateData() {
      if (!this.receivedData.length) {
        this.$message({
          message: '请先导入数据',
          type: 'warning'
        });
        return;
      }

      this.tableLoading = true;
      this.currentPage = 1; // 重置页码

      setTimeout(() => {
        try {
          const data = [
            ["编号", "x", "y", "高程"],
            ...this.receivedData,
          ];

          const { max, min, difference, dividedDifference } = this.calculateMinMax(this.receivedData);
          const yValuesMap = this.processYValues(this.receivedData);
          const processedData = data.slice(1);
          const sheet3Data = this.processSheet3Data(processedData, yValuesMap, max, dividedDifference);
          const minMaxData = [
            ["最大值", "最小值", "差值", "刀数"],
            [max === -Infinity ? null : max, min === Infinity ? null : min, difference, dividedDifference],
          ];

          this.calculatedData = {
            originalData: data,
            minMaxData,
            sheet3Data,
            dividedDifference
          };

          this.currentSheet = 'sheet1';
          this.handleSheetChange('sheet1');

          this.$message({
            message: '数据计算完成',
            type: 'success'
          });
        } catch (error) {
          console.error('计算错误:', error);
          this.$message.error('数据计算出错，请检查数据格式');
        } finally {
          this.tableLoading = false;
        }
      }, 0);
    },

    exportToExcel() {
      if (!this.calculatedData) {
        this.$message({
          message: '请先计算数据',
          type: 'warning'
        });
        return;
      }

      const { originalData, minMaxData, sheet3Data, dividedDifference } = this.calculatedData;
      const workbook = this.createWorkbook(originalData, minMaxData, sheet3Data, dividedDifference);
      XLSX.writeFile(workbook, "导出数据.xlsx");

      this.$message({
        message: '导出成功',
        type: 'success'
      });
    },

    getColumnWidth(header) {
      if (header.startsWith('CVN_')) {
        return 100;
      }
      switch (header) {
        case '编号':
          return 80;
        case 'x':
        case 'y':
          return 120;
        case '高程':
          return 120;
        case '标记':
          return 80;
        case '打印深度':
          return 120;
        default:
          return 100;
      }
    },

    handleSheetChange(sheetType) {
      this.tableLoading = true;
      this.currentPage = 1; // 重置页码

      if (this.dataCache.has(sheetType)) {
        const cachedData = this.dataCache.get(sheetType);
        this.currentHeaders = cachedData.headers;
        this.currentTableData = cachedData.data;
        this.totalRows = cachedData.data.length;
        this.updatePaginatedData();
        this.tableLoading = false;
        return;
      }

      requestAnimationFrame(() => {
        let headers = [];
        let data = [];

        switch(sheetType) {
          case 'sheet1':
            headers = this.calculatedData.originalData[0];
            data = this.calculatedData.originalData.slice(1);
            break;
          case 'sheet3':
            headers = this.calculatedData.sheet3Data[0];
            data = this.calculatedData.sheet3Data.slice(1);
            break;
          default:
            if (sheetType.startsWith('cvn')) {
              const cvnIndex = parseInt(sheetType.slice(3)) - 1;
              headers = ["编号", "x", "y", "标记", `CVN_${cvnIndex + 1}`];
              data = this.processDataForCVN(cvnIndex);
            }
        }

        this.dataCache.set(sheetType, {
          headers,
          data,
        });

        this.currentHeaders = headers;
        this.currentTableData = data;
        this.totalRows = data.length;
        this.updatePaginatedData();
        this.tableLoading = false;
      });
    },

    processDataForCVN(cvnIndex) {
      return this.calculatedData.sheet3Data
        .slice(1)
        .filter(item => item[6 + cvnIndex] !== -99)
        .map(item => [
          item[0], 
          item[1], 
          item[2], 
          item[4], 
          item[6 + cvnIndex]
        ]);
    },

    resetCache() {
      this.dataCache.clear();
    },

    formatCellValue(value) {
      if (typeof value === 'number') {
        return value.toFixed(3);
      }
      return value;
    },

    getCellClass(header, value) {
      if (header === '标记') {
        return `mark-${value?.toLowerCase()}`;
      }
      return '';
    },

    tableHeaderStyle() {
      return {
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 'bold',
        fontSize: '14px'
      };
    },

    tableCellStyle() {
      return {
        fontSize: '13px'
      };
    },

    // 更新分页数据
    updatePaginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedData = this.currentTableData.slice(start, end);
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.updatePaginatedData();
    },

    // 处理每页条数变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.updatePaginatedData();
    },
  },
};
</script>

<style scoped>
.daochu-container {
  padding: 20px;
}

.results-section {
  margin-top: 20px;
}

.stats-card {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}

.el-card {
  border-radius: 8px;
}

.el-card__header {
  padding: 15px 20px;
  font-weight: bold;
  background-color: #f5f7fa;
}

.el-button-group {
  margin-bottom: 20px;
}

.el-statistic {
  text-align: center;
}

/* 自定义表格样式 */
.el-table {
  margin-top: 10px;
}

.el-table th {
  background-color: #f5f7fa !important;
}

/* 响应式布局调整 */
@media screen and (max-width: 768px) {
  .el-col {
    margin-bottom: 15px;
  }
}

.sheet-selector {
  float: right;
  margin-top: -5px;
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

/* 标记样式 */
.mark-a {
  color: #67C23A;
  font-weight: bold;
}

.mark-b {
  color: #409EFF;
  font-weight: bold;
}

.mark-c {
  color: #E6A23C;
  font-weight: bold;
}

/* 数值单元格样式 */
.el-table .cell {
  padding: 8px 0;
}

/* 表格hover效果 */
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f0f9eb !important;
}

/* 响应式布局调整 */
@media screen and (max-width: 768px) {
  .sheet-selector {
    float: none;
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }
  
  .el-radio-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .el-radio-button {
    margin: 5px;
  }
}

/* 添加虚拟滚动相关样式 */
.el-table__virtual-wrapper {
  overflow-y: auto;
}

.el-table__virtual-scroll {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 优化表格样式 */
.el-table {
  margin-bottom: 0;
}

/* 优化分页器样式 */
.el-pagination {
  padding: 15px 0;
  background-color: #fff;
}

@media screen and (max-width: 768px) {
  .pagination-container {
    flex-direction: column;
    align-items: center;
  }
  
  .el-pagination {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 10px;
  }
}
</style>
